import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask import current_app
from flask import g
from flask import render_template
from flask import session
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from flask.ext.wtf.csrf import generate_csrf
from redis import StrictRedis
from config import config
# from info.utils.common import user_login_data


db = SQLAlchemy()
redis_st = None # type: StrictRedis

def set_up_loglevel(configname):
    logging.basicConfig(level=config[configname].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def creat_app(con):
    app = Flask(__name__)
    app.config.from_object(config[con])
    db.init_app(app)
    global redis_st
    redis_st = StrictRedis(host=config[con].HOST, port=config[con].PORT, decode_responses= True)
    # redis_st.set('xiaoxiaoxiaoxiaoxiao', 'mingmmingmingming')
    CSRFProtect(app)
    Session(app)
    from info.utils.common import choose
    app.add_template_filter(choose, 'choose_class')

    from info.utils.common import user_login_data
    @app.errorhandler(404)
    @user_login_data
    def errhander(e):
        current_app.logger.error(e)
        user = g.user
        data = {
            "user_info" : user.to_dict()
        }
        return render_template("news/404.html", data = data)

    # @app.add_template_filter('choose1')
    # def choo(num):
    #     if num == 1:
    #         return 'first'
    #     elif num == 2:
    #         return 'second'
    #     elif num == 3:
    #         return 'third'
    #     else:
    #         return ''   　为什么不能使用装饰器实现?
    # 生成csrf_token 并且设置在session中附在response上
    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response



    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    return app